import { reactive, computed, watch } from 'vue'
import { storageAPI } from '../api/storage.js'

// 任务优先级枚举
export const PRIORITY = {
  LOW: 'low',
  MEDIUM: 'medium',
  HIGH: 'high'
}

// 任务状态枚举
export const TASK_STATUS = {
  PENDING: 'pending',
  IN_PROGRESS: 'in_progress',
  COMPLETED: 'completed',
  ABANDONED: 'abandoned'
}

// 循环类型枚举
export const REPEAT_TYPE = {
  NONE: 'none',
  DAILY: 'daily',
  WEEKLY: 'weekly',
  MONTHLY: 'monthly'
}

// 全局状态管理
const state = reactive({
  // 清单列表
  lists: [],
  
  // 任务列表
  tasks: [],
  
  // 当前选中的清单
  currentListId: null,
  
  // 当前选中的任务过滤视图（today, tomorrow, high, medium等）
  currentView: 'inbox',
  
  // 当前显示模式（list 或 calendar）
  displayMode: 'list',
  
  // 数据加载状态
  isLoading: false,
  isInitialized: false
})

// 数据持久化相关函数
const persistence = {
  // 从存储加载数据
  async loadData() {
    try {
      state.isLoading = true
      const data = await storageAPI.getAllData()
      
      if (data && data.lists && data.tasks) {
        state.lists = data.lists
        state.tasks = data.tasks
        console.log('数据加载成功:', { lists: data.lists.length, tasks: data.tasks.length })
      } else {
        console.log('使用默认数据')
        // 创建默认清单
        state.lists = [
          {
            id: 'default-list-' + Date.now(),
            name: '我的清单',
            color: '#6366f1',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }
        ]
        state.tasks = []
        // 保存默认数据
        await persistence.saveAllData()
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      // 使用默认数据
    } finally {
      state.isLoading = false
      state.isInitialized = true
    }
  },
  
  // 保存所有数据
  async saveAllData() {
    try {
      await storageAPI.saveAllData(state.lists, state.tasks)
      console.log('数据保存成功')
    } catch (error) {
      console.error('保存数据失败:', error)
    }
  },
  
  // 保存清单数据
  async saveLists() {
    try {
      await storageAPI.saveLists(state.lists)
    } catch (error) {
      console.error('保存清单失败:', error)
    }
  },
  
  // 保存任务数据
  async saveTasks() {
    try {
      await storageAPI.saveTasks(state.tasks)
    } catch (error) {
      console.error('保存任务失败:', error)
    }
  }
}

// 监听数据变化，自动保存
let saveTimeout = null
const debouncedSave = () => {
  if (saveTimeout) clearTimeout(saveTimeout)
  saveTimeout = setTimeout(() => {
    if (state.isInitialized) {
      persistence.saveAllData()
    }
  }, 500) // 500ms防抖
}

// 监听lists变化
watch(() => state.lists, () => {
  debouncedSave()
}, { deep: true })

// 监听tasks变化
watch(() => state.tasks, () => {
  debouncedSave()
}, { deep: true })

// 计算属性
const getters = {
  // 获取所有清单（排除已删除的清单）
  customLists: computed(() => {
    return state.lists.filter(list => !list.deleted_at)
  }),

  // 获取所有清单（排除已删除的）
  allLists: computed(() => {
    return state.lists.filter(list => !list.deleted_at)
  }),

  // 获取当前清单的任务（排除已删除的任务）
  currentTasks: computed(() => {
    // 过滤掉已删除的任务
    const activeTasks = state.tasks.filter(task => !task.deleted_at)
    
    if (state.currentView === 'inbox') {
      // 收件箱显示无清单的未完成任务
      return activeTasks.filter(task => 
        (!task.listId || task.listId === '') && !task.completed
      )
    }
    
    if (state.currentView === 'today') {
      const today = new Date().toDateString()
      return activeTasks.filter(task => {
        // 检查开始时间或到期时间是否在今天
        if (task.startTime) {
          const startDate = new Date(task.startTime).toDateString()
          if (startDate === today) return true
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate).toDateString()
          if (dueDate === today) return true
        }
        return false
      })
    }
    
    if (state.currentView === 'tomorrow') {
      const tomorrow = new Date()
      tomorrow.setDate(tomorrow.getDate() + 1)
      const tomorrowStr = tomorrow.toDateString()
      return activeTasks.filter(task => {
        // 检查开始时间或到期时间是否在明天
        if (task.startTime) {
          const startDate = new Date(task.startTime).toDateString()
          if (startDate === tomorrowStr) return true
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate).toDateString()
          if (dueDate === tomorrowStr) return true
        }
        return false
      })
    }
    
    if (state.currentView === 'thisweek') {
      const now = new Date()
      // 计算本周的开始（周一）和结束（周日）
      const dayOfWeek = now.getDay() // 0=周日, 1=周一, ..., 6=周六
      const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1 // 计算到周一的天数
      const weekStart = new Date(now)
      weekStart.setDate(now.getDate() - daysToMonday)
      weekStart.setHours(0, 0, 0, 0) // 设置为当天开始
      
      const weekEnd = new Date(weekStart)
      weekEnd.setDate(weekStart.getDate() + 6)
      weekEnd.setHours(23, 59, 59, 999) // 设置为当天结束
      
      return activeTasks.filter(task => {
        // 检查开始时间或到期时间是否在本周内
        if (task.startTime) {
          const startDate = new Date(task.startTime)
          if (startDate >= weekStart && startDate <= weekEnd) return true
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate)
          if (dueDate >= weekStart && dueDate <= weekEnd) return true
        }
        return false
      })
    }
    
    if (state.currentView === 'planned') {
      // 所有任务视图：显示所有未删除的任务，不区分时间、清单归属
      return activeTasks
    }
    
    if (state.currentView === 'completed') {
      return activeTasks.filter(task => task.completed)
    }
    
    if (state.currentView === 'abandoned') {
      return activeTasks.filter(task => task.status === TASK_STATUS.ABANDONED)
    }
    
    if (state.currentView === 'high') {
      return activeTasks.filter(task => task.priority === PRIORITY.HIGH && !task.completed)
    }
    
    if (state.currentView === 'medium') {
      return activeTasks.filter(task => task.priority === PRIORITY.MEDIUM && !task.completed)
    }
    
    if (state.currentView === 'low') {
      return activeTasks.filter(task => task.priority === PRIORITY.LOW && !task.completed)
    }
    

    
    // 如果选择了特定清单，显示该清单的所有任务（包括已完成，但排除已删除）
    if (state.currentListId) {
      console.log('🔍 过滤特定清单任务:', {
        currentListId: state.currentListId,
        activeTasks: activeTasks.length,
        tasksWithListId: activeTasks.map(t => ({ id: t.id, title: t.title, listId: t.listId }))
      });
      const filteredTasks = activeTasks.filter(task => task.listId === state.currentListId);
      console.log('过滤后的任务:', filteredTasks.map(t => ({ id: t.id, title: t.title, listId: t.listId })));
      return filteredTasks;
    }
    
    // 默认返回收件箱任务
    return activeTasks.filter(task => (!task.listId || task.listId === '') && !task.completed)
  }),
  
  // 获取各个视图的任务数量
  taskCounts: computed(() => {
    const today = new Date().toDateString()
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    
    const now = new Date()
    // 计算本周的开始（周一）和结束（周日）
    const dayOfWeek = now.getDay() // 0=周日, 1=周一, ..., 6=周六
    const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1 // 计算到周一的天数
    const weekStart = new Date(now)
    weekStart.setDate(now.getDate() - daysToMonday)
    weekStart.setHours(0, 0, 0, 0) // 设置为当天开始
    
    const weekEnd = new Date(weekStart)
    weekEnd.setDate(weekStart.getDate() + 6)
    weekEnd.setHours(23, 59, 59, 999) // 设置为当天结束
    
    return {
      inbox: state.tasks.filter(task => 
        !task.deleted_at && !task.completed && (!task.listId || task.listId === '')
      ).length,
      
      today: state.tasks.filter(task => {
        if (task.deleted_at || task.completed) return false
        // 检查开始时间或到期时间是否在今天
        if (task.startTime) {
          const startDate = new Date(task.startTime).toDateString()
          if (startDate === today) return true
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate).toDateString()
          if (dueDate === today) return true
        }
        return false
      }).length,
      
      tomorrow: state.tasks.filter(task => {
        if (task.deleted_at || task.completed) return false
        const tomorrowStr = tomorrow.toDateString()
        // 检查开始时间或到期时间是否在明天
        if (task.startTime) {
          const startDate = new Date(task.startTime).toDateString()
          if (startDate === tomorrowStr) return true
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate).toDateString()
          if (dueDate === tomorrowStr) return true
        }
        return false
      }).length,
      
      thisweek: state.tasks.filter(task => {
        if (task.deleted_at || task.completed) return false
        // 检查开始时间或到期时间是否在本周内
        if (task.startTime) {
          const startDate = new Date(task.startTime)
          if (startDate >= weekStart && startDate <= weekEnd) return true
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate)
          if (dueDate >= weekStart && dueDate <= weekEnd) return true
        }
        return false
      }).length,
      
      planned: state.tasks.filter(task => !task.deleted_at).length,
      
      completed: state.tasks.filter(task => !task.deleted_at && task.completed).length,
      
      abandoned: state.tasks.filter(task => !task.deleted_at && task.status === TASK_STATUS.ABANDONED).length,
      
      high: state.tasks.filter(task => !task.deleted_at && task.priority === PRIORITY.HIGH && !task.completed).length,
      
      medium: state.tasks.filter(task => !task.deleted_at && task.priority === PRIORITY.MEDIUM && !task.completed).length,
      
      low: state.tasks.filter(task => !task.deleted_at && task.priority === PRIORITY.LOW && !task.completed).length
    }
  }),
  
  // 获取当前清单（排除已删除的）
  currentList: computed(() => {
    return state.lists.find(list => list.id === state.currentListId && !list.deleted_at)
  }),
  
  // 获取统计数据（排除已删除的任务）
  statistics: computed(() => {
    const currentTasks = getters.currentTasks.value
    const pendingTasks = currentTasks.filter(task => !task.completed && !task.deleted_at)
    const completedTasks = currentTasks.filter(task => task.completed && !task.deleted_at)
    
    return {
      estimatedTime: pendingTasks.reduce((total, task) => total + ((task.pomodoroRequired || 1) * 25), 0),
      pendingTasks: pendingTasks.length,
      completedTime: completedTasks.reduce((total, task) => total + ((task.pomodoroCount || 0) * 25), 0),
      completedTasks: completedTasks.length
    }
  })
}

// 操作方法
const actions = {
  // 创建新清单
  createList(name, color = '#6366f1') {
    // 处理CSS变量，转换为实际颜色值
    let processedColor = color
    if (color && color.startsWith('var(')) {
      // 如果是CSS变量，使用默认颜色
      processedColor = '#6366f1'
    }
    
    const newList = {
      id: Date.now().toString(),
      name,
      color: processedColor,
      createdAt: new Date().toISOString()
    }
    state.lists.push(newList)
    return newList
  },
  
  // 更新清单
  updateList(listId, updates) {
    const listIndex = state.lists.findIndex(list => list.id === listId)
    if (listIndex > -1) {
      // 处理color字段的CSS变量
      if (updates.color && updates.color.startsWith('var(')) {
        updates.color = '#6366f1' // 转换CSS变量为默认颜色
      }
      
      state.lists[listIndex] = {
        ...state.lists[listIndex],
        ...updates,
        updatedAt: new Date().toISOString()
      }
    }
  },

  // 删除清单（软删除）
  deleteList(listId) {
    // 检查清单是否存在
    const listToDelete = state.lists.find(list => list.id === listId)
    if (!listToDelete) {
      console.warn('清单不存在')
      return
    }
    
    const list = state.lists.find(list => list.id === listId)
    if (list) {
      // 软删除：标记deleted_at字段
      list.deleted_at = new Date().toISOString()
      list.updatedAt = new Date().toISOString()
      
      // 将清单下的所有任务标记为删除
      const deletedTasksCount = state.tasks.filter(task => 
        task.listId === listId && !task.deleted_at
      ).length
      
      state.tasks.forEach(task => {
        if (task.listId === listId && !task.deleted_at) {
          // 软删除：标记deleted_at字段
          task.deleted_at = new Date().toISOString()
          task.updatedAt = new Date().toISOString()
        }
      })
      
      // 如果删除的是当前清单，切换到收件箱视图
      if (state.currentListId === listId) {
        state.currentListId = null
        state.currentView = 'inbox'
      }
      
      console.log(`删除清单 "${list.name}" 及其下属的 ${deletedTasksCount} 个任务`)
    }
  },

  // 移动任务到指定清单
  moveTaskToList(taskId, targetListId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.listId = targetListId ? targetListId.toString() : ''
      task.updatedAt = new Date().toISOString()
    }
  },
  
  // 切换当前清单
  setCurrentList(listId) {
    state.currentListId = listId
    // 选择清单时清除视图状态
    state.currentView = null
  },
  
  // 切换当前视图
  setCurrentView(view) {
    state.currentView = view
    // 切换视图时清除清单选择
    state.currentListId = null
  },
  
  // 添加任务
  addTask(text, listId = state.currentListId, options = {}) {
    // 生成唯一ID，确保不与现有任务重复
    let newId;
    do {
      newId = Date.now() + Math.floor(Math.random() * 1000);
    } while (state.tasks.some(task => task.id === newId));
    
    const newTask = {
      id: newId,
      text,
      title: text, // 添加title字段
      listId: listId ? listId.toString() : '',
      completed: false,
      priority: options.priority || PRIORITY.MEDIUM,
      pomodoroCount: 0,
      pomodoroCompleted: 0, // 添加pomodoroCompleted字段
      pomodoroRequired: options.pomodoroRequired || 1,
      status: TASK_STATUS.PENDING,
      dueDate: options.dueDate || null, // 允许到期时间为空，不设置默认值
      startTime: options.startTime || new Date().toISOString(), // 添加开始时间字段
      repeatType: options.repeatType || REPEAT_TYPE.NONE,
      recurrence: options.recurrence || options.repeatType || 'none', // 添加recurrence字段以兼容模板
      notes: options.notes || '', // 添加notes字段
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    state.tasks.push(newTask)
    return newTask
  },
  
  // 更新任务
  updateTask(taskId, updates) {
    const taskIndex = state.tasks.findIndex(task => task.id === taskId)
    if (taskIndex > -1) {
      const currentTask = state.tasks[taskIndex]
      
      // 确保listId是字符串类型
      const processedUpdates = { ...updates }
      if (processedUpdates.listId !== undefined) {
        processedUpdates.listId = processedUpdates.listId ? processedUpdates.listId.toString() : ''
      }
      
      // 同步recurrence和repeatType字段
      if (processedUpdates.recurrence !== undefined) {
        processedUpdates.repeatType = processedUpdates.recurrence
      }
      if (processedUpdates.repeatType !== undefined) {
        processedUpdates.recurrence = processedUpdates.repeatType
      }
      
      // 递增版本号
      const currentVersion = parseInt(currentTask.version) || 1
      const newVersion = currentVersion + 1
      
      console.log('🔄 更新任务版本:', {
        taskId,
        title: currentTask.title,
        currentVersion,
        newVersion,
        updates: Object.keys(processedUpdates)
      })
      
      state.tasks[taskIndex] = {
        ...currentTask,
        ...processedUpdates,
        version: newVersion,
        updatedAt: new Date().toISOString()
      }
    }
  },
  
  // 切换任务完成状态
  toggleTask(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.completed = !task.completed
      task.status = task.completed ? TASK_STATUS.COMPLETED : TASK_STATUS.PENDING
      
      // 设置完成时间
      if (task.completed) {
        task.completed_at = new Date().toISOString()
      } else {
        // 如果取消完成，清除完成时间
        delete task.completed_at
      }
      
      // 递增版本号
      const currentVersion = parseInt(task.version) || 1
      const newVersion = currentVersion + 1
      task.version = newVersion
      task.updatedAt = new Date().toISOString()
      
      console.log('🔄 toggleTask 版本更新:', {
        taskId: task.id,
        title: task.title,
        completed: task.completed,
        currentVersion,
        newVersion
      })
    }
  },
  
  // 切换任务完成状态（别名方法）
  toggleTaskCompleted(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      // 检查是否为重复任务且尝试取消完成
      if (task.completed === true) { // 即将被取消完成
        const repeatType = (task.recurrence && task.recurrence !== 'none') ? task.recurrence : task.repeatType
        const isRepeatTask = repeatType && repeatType !== REPEAT_TYPE.NONE && repeatType !== 'none'
        
        // 如果是已完成的重复任务，不允许取消完成状态
        if (isRepeatTask) {
          // 触发全局事件来显示提示信息
          window.dispatchEvent(new CustomEvent('showRepeatTaskCompleteError', {
            detail: {
              taskTitle: task.title || task.text,
              message: '已完成的重复任务不能修改为未完成状态'
            }
          }))
          return false // 返回false表示操作失败
        }
      }
      
      // 检查是否为重复任务且尝试完成
      if (task.completed === false) { // 即将被标记为完成
        const repeatType = (task.recurrence && task.recurrence !== 'none') ? task.recurrence : task.repeatType
        const isRepeatTask = repeatType && repeatType !== REPEAT_TYPE.NONE && repeatType !== 'none'
        
        // 如果是重复任务，检查开始时间
        if (isRepeatTask && task.startTime) {
          const now = new Date()
          const startTime = new Date(task.startTime)
          
          if (startTime > now) {
            // 重复任务还未到开始时间，不允许完成
            const formatDate = (date) => {
              return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
              })
            }
            
            // 触发全局事件来显示模态框
            window.dispatchEvent(new CustomEvent('showRepeatTaskTimeError', {
              detail: {
                taskTitle: task.title || task.text,
                startDate: formatDate(startTime),
                currentDate: formatDate(now)
              }
            }))
            return false // 返回false表示操作失败
          }
        }
      }
      
      task.completed = !task.completed
      task.status = task.completed ? TASK_STATUS.COMPLETED : TASK_STATUS.PENDING
      
      // 设置完成时间
      if (task.completed) {
        task.completed_at = new Date().toISOString()
        
        // 处理重复任务逻辑 - 检查repeatType和recurrence字段
        // 优先使用 recurrence 字段，如果 recurrence 为空或 'none' 才使用 repeatType
        const repeatType = (task.recurrence && task.recurrence !== 'none') ? task.recurrence : task.repeatType
        console.log('🔄 重复任务检查:', {
          taskId: task.id,
          title: task.title || task.text,
          repeatType: task.repeatType,
          recurrence: task.recurrence,
          finalRepeatType: repeatType,
          isRepeating: !!(repeatType && repeatType !== REPEAT_TYPE.NONE && repeatType !== 'none')
        })
        
        if (repeatType && repeatType !== REPEAT_TYPE.NONE && repeatType !== 'none') {
          console.log('🔄 开始创建重复任务...')
          
          // 如果原始任务还没有recurring_series_id，设置为自己的ID
          if (!task.recurring_series_id) {
            task.recurring_series_id = task.id
            task.updatedAt = new Date().toISOString()
          }
          
          // 避免使用this，直接调用actions内部的方法
          const newTask = actions.createNextRecurringTask(task)
          if (newTask) {
            console.log('✅ 重复任务创建成功:', {
              newTaskId: newTask.id,
              newTaskTitle: newTask.title,
              newStartTime: newTask.startTime
            })
          } else {
            console.log('❌ 重复任务创建失败')
          }
        } else {
          console.log('⏹️ 任务不是重复任务，跳过创建')
        }
      } else {
        // 如果取消完成，清除完成时间
        delete task.completed_at
      }
      
      // 如果任务被标记为完成，且没有完成任何番茄钟，则将番茄钟计数设置为所需数量
      if (task.completed && (task.pomodoroCount || 0) === 0) {
        task.pomodoroCount = task.pomodoroRequired || 1
        task.pomodoroCompleted = task.pomodoroRequired || 1
      }
      // 如果任务被取消完成，重置番茄钟计数
      else if (!task.completed && task.pomodoroCount === task.pomodoroRequired) {
        task.pomodoroCount = 0
        task.pomodoroCompleted = 0
      }
      
      // 递增版本号
      const currentVersion = parseInt(task.version) || 1
      const newVersion = currentVersion + 1
      task.version = newVersion
      task.updatedAt = new Date().toISOString()
      
      console.log('🔄 任务完成状态切换:', {
        taskId: task.id,
        title: task.title || task.text,
        completed: task.completed,
        currentVersion,
        newVersion,
        pomodoroCount: task.pomodoroCount,
        pomodoroCompleted: task.pomodoroCompleted,
        pomodoroRequired: task.pomodoroRequired,
        totalPomodoroTime: task.completed ? (task.pomodoroCount || 0) * 25 : 0,
        repeatType: task.repeatType
      })
      
      return true // 返回true表示操作成功
    }
  },
  
  // 删除任务（软删除）
  deleteTask(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      // 软删除：标记deleted_at字段
      task.deleted_at = new Date().toISOString()
      task.updatedAt = new Date().toISOString()
    }
  },

  // 放弃任务
  abandonTask(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.status = TASK_STATUS.ABANDONED
      task.updatedAt = new Date().toISOString()
      persistence.saveAllData()
    }
  },

  // 恢复已放弃的任务
  restoreTask(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task && task.status === TASK_STATUS.ABANDONED) {
      task.status = TASK_STATUS.PENDING
      task.updatedAt = new Date().toISOString()
      persistence.saveAllData()
    }
  },

  // 创建下一个重复任务
  createNextRecurringTask(originalTask) {
    console.log('🔄 计算下次重复时间，原任务信息:', {
      id: originalTask.id,
      title: originalTask.title,
      repeatType: originalTask.repeatType,
      recurrence: originalTask.recurrence,
      startTime: originalTask.startTime
    })
    
    const nextDate = this.calculateNextRecurrenceDate(originalTask)
    console.log('🔄 计算结果 - 下次重复时间:', nextDate)
    
    if (!nextDate) {
      console.log('❌ 无法计算下次重复时间，创建失败')
      return null
    }
    
    // 创建新的重复任务
    let newId;
    do {
      newId = Date.now() + Math.floor(Math.random() * 1000);
    } while (state.tasks.some(task => task.id === newId));
    
    // 保持原始任务的时间部分（小时、分钟、秒）
    const originalStartTime = new Date(originalTask.startTime || originalTask.createdAt)
    const newStartTime = new Date(nextDate)
    
    // 设置新任务的开始时间，保持原始任务的具体时间
    newStartTime.setHours(
      originalStartTime.getHours(),
      originalStartTime.getMinutes(),
      originalStartTime.getSeconds(),
      originalStartTime.getMilliseconds()
    )
    
    // 如果原始任务有结束时间，计算新的结束时间，保持时间间隔一致
    let newDueDate = null
    if (originalTask.dueDate) {
      const originalDueTime = new Date(originalTask.dueDate)
      const timeDifference = originalDueTime.getTime() - originalStartTime.getTime()
      newDueDate = new Date(newStartTime.getTime() + timeDifference)
    }

    // 为重复任务添加唯一标识，避免内容冲突
    const newTask = {
      ...originalTask,
      id: newId,
      completed: false,
      status: TASK_STATUS.PENDING,
      startTime: newStartTime.toISOString(),
      dueDate: newDueDate ? newDueDate.toISOString() : null,
      pomodoroCount: 0,
      pomodoroCompleted: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      completed_at: undefined,
      // 添加重复任务标识字段，避免同步冲突
      created_from_task_id: originalTask.id, // 记录创建来源
      recurring_series_id: originalTask.recurring_series_id || originalTask.id, // 重复任务系列ID
      recurring_instance_date: newStartTime.toISOString() // 当前实例的日期标识
    }
    
    state.tasks.push(newTask)
    console.log('🔄 创建重复任务成功:', {
      originalTitle: originalTask.title,
      newTaskId: newTask.id,
      newTitle: newTask.title,
      nextStartTime: nextDate.toISOString(),
      tasksCount: state.tasks.length
    })
    return newTask
  },

  // 计算下一次重复时间
  calculateNextRecurrenceDate(task) {
    const now = new Date()
    const originalStartTime = new Date(task.startTime || task.createdAt)
    let nextDate = new Date(originalStartTime)
    
    // 获取重复类型，支持repeatType和recurrence字段
    // 优先使用 recurrence 字段，如果 recurrence 为空或 'none' 才使用 repeatType
    const repeatType = (task.recurrence && task.recurrence !== 'none') ? task.recurrence : task.repeatType
    
    console.log('🔄 计算重复时间详情:', {
      now: now.toISOString(),
      originalStartTime: originalStartTime.toISOString(),
      repeatType: repeatType,
      REPEAT_TYPE_DAILY: REPEAT_TYPE.DAILY,
      REPEAT_TYPE_WEEKLY: REPEAT_TYPE.WEEKLY,
      REPEAT_TYPE_MONTHLY: REPEAT_TYPE.MONTHLY
    })
    
    // 根据重复类型计算下次时间
    switch (repeatType) {
      case REPEAT_TYPE.DAILY:
      case 'daily':
        // console.log('🔄 处理每日重复')
        nextDate.setDate(originalStartTime.getDate() + 1)
        break
      case REPEAT_TYPE.WEEKLY:
      case 'weekly':
        // console.log('🔄 处理每周重复')
        nextDate.setDate(originalStartTime.getDate() + 7)
        break
      case REPEAT_TYPE.MONTHLY:
      case 'monthly':
        // console.log('🔄 处理每月重复')
        nextDate.setMonth(originalStartTime.getMonth() + 1)
        break
      default:
        // console.log('❌ 未知的重复类型:', repeatType)
        return null
    }
    
    // console.log('🔄 初步计算的下次时间:', nextDate.toISOString())
    
    // 如果计算出的下次时间已经过期，则从当前时间开始计算
    if (nextDate <= now) {
      const timePart = {
        hours: originalStartTime.getHours(),
        minutes: originalStartTime.getMinutes(),
        seconds: originalStartTime.getSeconds()
      }
      
      nextDate = new Date(now)
      nextDate.setDate(now.getDate() + 1) // 从明天开始
      nextDate.setHours(timePart.hours, timePart.minutes, timePart.seconds, 0)
      
      // 如果是周重复或月重复，需要特殊处理
      if (repeatType === REPEAT_TYPE.WEEKLY || repeatType === 'weekly') {
        const targetDayOfWeek = originalStartTime.getDay()
        const currentDayOfWeek = nextDate.getDay()
        const daysToAdd = (targetDayOfWeek - currentDayOfWeek + 7) % 7
        if (daysToAdd === 0) {
          nextDate.setDate(nextDate.getDate() + 7) // 下周同一天
        } else {
          nextDate.setDate(nextDate.getDate() + daysToAdd)
        }
      } else if (repeatType === REPEAT_TYPE.MONTHLY || repeatType === 'monthly') {
        const targetDate = originalStartTime.getDate()
        nextDate.setDate(1) // 设置为月初
        nextDate.setMonth(nextDate.getMonth() + 1) // 下个月
        
        // 处理月末日期（如31号在2月不存在的情况）
        const lastDayOfMonth = new Date(nextDate.getFullYear(), nextDate.getMonth() + 1, 0).getDate()
        nextDate.setDate(Math.min(targetDate, lastDayOfMonth))
      }
    }
    
    return nextDate
  },

  // 调整到期时间
  adjustDueDate(originalDueDate, originalStartTime, newStartTime) {
    if (!originalDueDate || !originalStartTime) return null
    
    const originalDue = new Date(originalDueDate)
    const originalStart = new Date(originalStartTime)
    const timeDiff = originalDue.getTime() - originalStart.getTime()
    
    return new Date(newStartTime.getTime() + timeDiff)
  },

  // 停止任务重复
  stopTaskRecurrence(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.repeatType = REPEAT_TYPE.NONE
      task.recurrence = 'none'
      task.updatedAt = new Date().toISOString()
    }
  },

  // 获取重复任务系列
  getRecurringTaskSeries(taskId) {
    const task = state.tasks.find(t => t.id === taskId)
    if (!task || !task.title) return []
    
    // 通过标题和重复类型找到相关的重复任务
    return state.tasks.filter(t => 
      t.title === task.title && 
      t.repeatType === task.repeatType &&
      t.repeatType !== REPEAT_TYPE.NONE &&
      !t.deleted_at
    ).sort((a, b) => new Date(a.startTime || a.createdAt) - new Date(b.startTime || b.createdAt))
  },
  
  // 开始任务（番茄钟）
  startTask(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.status = TASK_STATUS.IN_PROGRESS
      task.updatedAt = new Date().toISOString()
    }
  },
  
  // 完成一个番茄钟
  completePomodoro(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.pomodoroCount += 1
      task.updatedAt = new Date().toISOString()
      
      // 如果完成了所需的番茄钟数，自动标记任务为完成
      if (task.pomodoroCount >= task.pomodoroRequired) {
        task.completed = true
        task.status = TASK_STATUS.COMPLETED
        task.completed_at = new Date().toISOString()
      }
    }
  },
  
  // 完成任务的番茄钟（别名方法）
  completePomodoroForTask(taskId) {
    const task = state.tasks.find(task => task.id === taskId)
    if (task) {
      task.pomodoroCount += 1
      task.pomodoroCompleted += 1  // 同步更新pomodoroCompleted字段
      task.updatedAt = new Date().toISOString()
      
      // 如果完成了所需的番茄钟数，自动标记任务为完成
      if (task.pomodoroCount >= task.pomodoroRequired) {
        task.completed = true
        task.status = TASK_STATUS.COMPLETED
        task.completed_at = new Date().toISOString()
      }
    }
  },

  // 合并同步数据
  mergeSyncData(syncData) {
    
    // 合并清单数据
    if (syncData.lists && Array.isArray(syncData.lists)) {
      const serverLists = syncData.lists
      
      serverLists.forEach(serverList => {
        const existingIndex = state.lists.findIndex(list => 
          list.id === serverList.client_id || list.id === serverList.id
        )
        
        if (existingIndex > -1) {
          // 更新现有清单
          state.lists[existingIndex] = {
            ...state.lists[existingIndex],
            id: serverList.client_id || serverList.id,
            name: serverList.name,
            color: serverList.color,
            deleted_at: serverList.deleted_at,
            updatedAt: serverList.last_modified_at || serverList.updated_at || new Date().toISOString()
          }
        } else {
          // 添加新清单
          state.lists.push({
            id: serverList.client_id || serverList.id,
            name: serverList.name,
            color: serverList.color,
            deleted_at: serverList.deleted_at,
            createdAt: serverList.created_at || new Date().toISOString(),
            updatedAt: serverList.last_modified_at || serverList.updated_at || new Date().toISOString()
          })
        }
      })
    }
    
    if (syncData.tasks && Array.isArray(syncData.tasks)) {
      
      // 去重处理：使用Map来跟踪已处理的任务ID，避免重复
      const processedTaskIds = new Set()
      const processedTaskContent = new Set() // 添加内容去重
      
      syncData.tasks.forEach((serverTask, index) => {
        // 确定任务的唯一标识符
        const taskId = serverTask.client_id || serverTask.id
        
        // 创建任务内容的唯一标识符（基于标题、文本、截止日期、开始时间等）
        // 对于重复任务，添加重复任务标识字段以避免误判为重复内容
        const recurringInstanceDate = serverTask.recurring_instance_date || ''
        const createdFromTaskId = serverTask.created_from_task_id || ''
        const taskContentKey = `${serverTask.title || ''}-${serverTask.text || ''}-${serverTask.due_date || serverTask.dueDate || ''}-${serverTask.start_time || serverTask.startTime || ''}-${serverTask.listId || ''}-${recurringInstanceDate}-${createdFromTaskId}`
        
        // 检查ID重复（转换为字符串进行比较）
        const taskIdStr = String(taskId);
        const hasProcessedId = processedTaskIds.has(taskIdStr);
        
        // 同时检查本地是否已存在相同ID的任务（考虑类型转换）
        const existsInLocal = state.tasks.some(localTask => 
          String(localTask.id) === taskIdStr || 
          String(localTask.client_id) === taskIdStr
        );
        
        // 检查内容重复
        const hasProcessedContent = processedTaskContent.has(taskContentKey);
        
        // 如果已经处理过这个任务ID或相同内容的任务，跳过
        if (hasProcessedId || hasProcessedContent) {
          console.warn('跳过重复任务:', {
            taskId: taskIdStr,
            title: serverTask.title,
            reason: hasProcessedId ? 'ID重复' : '内容重复'
          })
          return
        }
        processedTaskIds.add(taskIdStr)
        processedTaskContent.add(taskContentKey)
        
        // 检查任务是否被删除
        if (serverTask.deleted_at) {
          console.log('🗑️ 处理已删除任务');
          // 从本地删除该任务
          const deleteIndex = state.tasks.findIndex(task => task.id === taskId);
          if (deleteIndex > -1) {
            console.log('删除本地任务:', state.tasks[deleteIndex]);
            state.tasks.splice(deleteIndex, 1);
            console.log('✅ 已删除任务从本地移除');
          } else {
            console.log('⚠️ 要删除的任务在本地不存在');
          }
          return;
        }
        
        // 查找本地是否存在该任务（考虑类型转换）
        const existingIndex = state.tasks.findIndex(task => 
          String(task.id) === taskIdStr
        )
        
        if (existingIndex > -1) {
          // 更新现有任务
          const updatedTask = {
            ...state.tasks[existingIndex],
            id: taskId,
            title: serverTask.title,
            text: serverTask.text,
            notes: serverTask.notes || '', // 添加notes字段映射
            completed: serverTask.completed,
            priority: serverTask.priority,
            listId: serverTask.listId ? serverTask.listId.toString() : (serverTask.list_id ? serverTask.list_id.toString() : null), // 优先使用后端返回的listId字段
            dueDate: serverTask.due_date || serverTask.dueDate, // 映射due_date到dueDate
            startTime: serverTask.start_time || serverTask.startTime, // 映射start_time到startTime
            status: serverTask.status,
            pomodoroRequired: serverTask.pomodoro_required || serverTask.pomodoroRequired,
            pomodoroCount: serverTask.pomodoro_count || serverTask.pomodoroCount,
            pomodoroCompleted: serverTask.pomodoro_completed || serverTask.pomodoroCompleted,
            completed_at: serverTask.completed_at || serverTask.completed_at, // 映射completed_at到completed_at
            repeatType: serverTask.repeat_type || serverTask.repeatType, // 映射repeat_type到repeatType
            recurrence: serverTask.recurrence, // 映射recurrence字段
            version: serverTask.version || 1, // 添加版本号支持
            recurring_series_id: serverTask.recurring_series_id, // 重复任务系列ID
            created_from_task_id: serverTask.created_from_task_id, // 创建来源任务ID
            is_recurring_parent: serverTask.is_recurring_parent || false, // 是否为重复任务父任务
            deleted_at: serverTask.deleted_at,
            updatedAt: serverTask.last_modified_at || serverTask.updated_at || new Date().toISOString()
          };
           state.tasks[existingIndex] = updatedTask;
         } else {
           const newTask = {
             id: taskId,
             title: serverTask.title,
             text: serverTask.text,
             notes: serverTask.notes || '', // 添加notes字段映射
             completed: serverTask.completed,
             priority: serverTask.priority,
             listId: serverTask.listId ? serverTask.listId.toString() : (serverTask.list_id ? serverTask.list_id.toString() : null), // 优先使用后端返回的listId字段
             dueDate: serverTask.due_date || serverTask.dueDate, // 映射due_date到dueDate
             startTime: serverTask.start_time || serverTask.startTime, // 映射start_time到startTime
             status: serverTask.status,
             pomodoroRequired: serverTask.pomodoro_required || serverTask.pomodoroRequired,
             pomodoroCount: serverTask.pomodoro_count || serverTask.pomodoroCount,
             pomodoroCompleted: serverTask.pomodoro_completed || serverTask.pomodoroCompleted,
             completed_at: serverTask.completed_at || serverTask.completed_at, // 映射completed_at到completed_at
             repeatType: serverTask.repeat_type || serverTask.repeatType, // 映射repeat_type到repeatType
             recurrence: serverTask.recurrence, // 映射recurrence字段
             version: serverTask.version || 1, // 添加版本号支持
             recurring_series_id: serverTask.recurring_series_id, // 重复任务系列ID
             created_from_task_id: serverTask.created_from_task_id, // 创建来源任务ID
             is_recurring_parent: serverTask.is_recurring_parent || false, // 是否为重复任务父任务
             deleted_at: serverTask.deleted_at,
             createdAt: serverTask.created_at || new Date().toISOString(),
             updatedAt: serverTask.last_modified_at || serverTask.updated_at || new Date().toISOString()
           };
           // 添加新任务
           state.tasks.push(newTask);
          }
        })
      }
    
    // 保存数据
    persistence.saveAllData()
  }
}

// 导出store
export const useTodoStore = () => {
  return {
    state,
    ...getters,
    ...actions,
    // 数据持久化方法
    loadData: persistence.loadData,
    saveAllData: persistence.saveAllData,
    saveLists: persistence.saveLists,
    saveTasks: persistence.saveTasks,
    // 清空所有数据
    async clearAllData() {
      try {
        await storageAPI.clearAllData()
        // 重置为默认数据
        state.lists = []
        state.tasks = []
        state.currentListId = null
        state.currentView = 'inbox'
        console.log('数据清空成功')
      } catch (error) {
        console.error('清空数据失败:', error)
      }
    },
    // 获取存储路径
    async getStorePath() {
      try {
        return await storageAPI.getStorePath()
      } catch (error) {
        console.error('获取存储路径失败:', error)
        return { path: '未知' }
      }
    },
    // 检查是否在Electron环境
    isElectron: storageAPI.isElectron
  }
}